﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace MediaCenterExractor
{
    static class MediaFilesHandler
    {
        public static void HandleFiles(string sourcePath, string finalPath)
        {
            try
            {
                if (!Directory.Exists(finalPath))
                    Directory.CreateDirectory(finalPath);

                var mkvFiles = Directory.GetFiles(sourcePath, "*.mkv", SearchOption.TopDirectoryOnly);
                CopyFiles(mkvFiles, finalPath);

                var aviFiles = Directory.GetFiles(sourcePath, "*.avi", SearchOption.TopDirectoryOnly);
                CopyFiles(aviFiles, finalPath);

                var mp4Files = Directory.GetFiles(sourcePath, "*.mp4", SearchOption.TopDirectoryOnly);
                CopyFiles(mp4Files, finalPath);

                var rarFiles = Directory.GetFiles(sourcePath, "*.rar", SearchOption.TopDirectoryOnly);
                ExractRars(rarFiles, finalPath);

            }
            catch (Exception ex)
            {
                Logger.Write("Error handling files:\n\r " + ex);
            }
        }

        private static void ExractRars(string[] rarFiles, string finalPath)
        {
            finalPath = finalPath.TrimEnd('\\');
            foreach (var file in rarFiles)
            {
                Logger.Write("Extracting video from: " + file);
                Logger.Write("Extracting video to: " + finalPath);
                Process.Start("Winrar", string.Format("e -o+ -ibck -y \"{0}\" *.* \"{1}\\\"", file, finalPath));
            }
        }

        private static void CopyFiles(string[] files, string finalPath)
        {
            foreach (var file in files)
            {
                Logger.Write("Copying video file from: " + file);
                
                var fileName = Path.GetFileName(file);

                var destFileName = Path.Combine(finalPath, fileName);

                Logger.Write("Copying video file to: " + destFileName);

                if (!File.Exists(destFileName))
                {
                    File.Copy(file, destFileName);
                }
            }
        }
    }
}
